﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net;
using Common;

namespace WXPackage
{
    /// <summary>
    /// 菜单管理
    /// 文档参阅：http://mp.weixin.qq.com/wiki/6/95cade7d98b6c1e1040cde5d9a2f9c26.html
    /// </summary>
    public class MenuManage : BaseManage
    {
        /// <summary>
        /// 菜单内容缓存
        /// </summary>
        private List<MenuButtonData> _list = null;
        /// <summary>
        /// 初始化
        /// </summary>
        public MenuManage()
        {
            _list = LoadData();
        }

        #region 常用操作
        /// <summary>
        /// 添加一级菜单
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool Add(MenuButtonData item)
        {
            item.ID = GetNextID();
            _list.Add(item);
            //保存磁盘
            Save();
            return true;
        }
        /// <summary>
        /// 添加一级菜单
        /// </summary>
        /// <param name="name">菜单名称</param>
        /// <param name="key">菜单key值</param>
        /// <param name="url">链接地址</param>
        /// <param name="media_id">调用新增永久素材接口返回的合法media_id</param>
        /// <returns></returns>
        public bool Add(string name, string key, string url, string media_id)
        {
            MenuButtonData item = new MenuButtonData();
            item.name = name;
            item.key = key;
            item.url = url;
            item.media_id = media_id;
            return Add(item);
        }
        /// <summary>
        /// 获取一级菜单
        /// </summary>
        /// <param name="SourceID"></param>
        /// <returns></returns>
        public MenuButtonData Get(int SourceID)
        {
            MenuButtonData item = _list.Where(q => q.ID == SourceID).FirstOrDefault();
            if (item == null)
            {
                foreach (var parent in _list)
                {
                    return parent.sub_button.Where(q => q.ID == SourceID).FirstOrDefault();
                }
            }
            return null;
        }
        /// <summary>
        /// 修改一级菜单
        /// </summary>
        /// <param name="SourceID"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool Update(int SourceID, MenuButtonData item)
        {
            MenuButtonData source = Get(SourceID);
            if (source == null)
                throw new Exception("修改菜单时，或菜单ID失败");
            source.name = item.name;
            source.key = item.key;
            source.url = item.url;
            source.media_id = item.media_id;
            Save();
            return true;
        }
        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public bool Remove(int ID)
        {
            foreach (var parent in _list)
            {
                if (parent.ID == ID)
                {
                    _list.Remove(parent);
                    return true;
                }
                else
                {
                    foreach (var child in parent.sub_button)
                    {
                        if (child.ID == ID)
                        {
                            parent.sub_button.Remove(child);
                            return true;
                        }
                    }
                }
            }
            return false;
        }
        /// <summary>
        /// 获取菜单ID
        /// </summary>
        /// <returns></returns>
        public int GetNextID()
        {
            int max = _list.Count > 0 ? _list.Max(q => q.ID) : 0;
            if (max == 0)
                return 1;
            int max2 = _list.Max(q => q.sub_button.Count > 0 ? q.sub_button.Max(i => i.ID) : 0);
            return Math.Max(max, max2) + 1;
        }
        #endregion

        #region 磁盘操作
        /// <summary>
        /// 将当前菜单保存到磁盘
        /// </summary>
        public void Save()
        {
            try
            {
                string filename = ConfigValue.DataPath + "menu.xml";
                XmlSerializerHelper _serialize = new XmlSerializerHelper(filename);
                _serialize.Serialize<List<MenuButtonData>>(_list);
            }
            catch (Exception ex)
            {
                LogOperate.Write("序列化保存菜单列表失败，" + ex.Message);
            }
        }
        /// <summary>
        /// 从磁盘获取菜单列表
        /// </summary>
        /// <returns></returns>
        public List<MenuButtonData> LoadData()
        {
            try
            {
                string filename = ConfigValue.DataPath + "menu.xml";
                XmlSerializerHelper _serialize = new XmlSerializerHelper(filename);
                return _serialize.Deserialize<List<MenuButtonData>>();
            }
            catch (Exception ex)
            {
                LogOperate.Write("序列化获取菜单列表失败，" + ex.Message);
                return new List<MenuButtonData>();
            }
        }
        #endregion

        #region 远程操作
        /// <summary>
        /// 去微信服务器，加载菜单
        /// </summary>
        /// <returns></returns>
        public List<MenuButtonData> LoadData_Remote()
        {
            List<MenuButtonData> list = new List<MenuButtonData>();
            string url = new LinkManage().GetQueryMenu();
            string result = NetHelper.Get(url);
            JObject obj = JObject.Parse(result);
            if (obj == null)
                return list;
            JToken menu = obj.SelectToken("menu.button");
            if (menu == null)
                return list;
            list = menu.Select(q => JsonConvert.DeserializeObject<MenuButtonData>(q.ToString()))
                 .ToList();
            return list;
        }
        /// <summary>
        /// 将本地数据，更新到微信服务器
        /// </summary>
        /// <returns></returns>
        public bool PostData_Remote()
        {
            try
            {
                string url = new LinkManage().GetCreateMenu();
                NetHelper.Post(url, GetJson_Remote());
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception("将本地菜单更新到服务器失败，" + ex.Message);
            }
        }
        /// <summary>
        /// 获取发送到微信服务器的json 数据结构
        /// </summary>
        /// <returns></returns>
        public string GetJson_Remote()
        {
            JObject button = JObject.FromObject(new
            {
                button = _list
            });
            return button.ToString();
        }
        /// <summary>
        /// 删除使用菜单
        /// </summary>
        /// <returns></returns>
        public string Delete_Remote()
        {
            string url = new LinkManage().GetRemoveMenu();
            string result = NetHelper.Get(url);
            JObject obj = JObject.Parse(result);
            string msg = (string)obj["errmsg"];
            if (msg == "ok")
                return "1";
            return msg;
        }
        #endregion
    }

    ///// <summary>
    ///// 菜单按钮列表
    ///// </summary>
    //public class MenuData
    //{
    //    public List<MenuButtonData> button { get; set; }
    //    public MenuData() {
    //        button = new List<WXPackage.MenuButtonData>();
    //    }
    //}

    /// <summary>
    /// 菜单按钮
    /// </summary>
    public class MenuButtonData
    {
        /// <summary>
        /// 菜单ID，本地使用
        /// </summary>
        [JsonIgnore()]
        public int ID { get; set; }
        /// <summary>
        /// 子菜单按钮列表
        /// </summary>
        public List<MenuButtonData> sub_button { get; set; }
        public MenuButtonData() {
            sub_button = new List<WXPackage.MenuButtonData>();
        }
        /// <summary>
        /// 判断当前是否是父节点
        /// </summary>
        public bool IsParent {
            get {
                return this.sub_button.Count == 0;
            }
        }
        /// <summary>
        /// 彩带标题，不超过16字节，子菜单不超过40字节
        /// </summary>
        public string name { get; set; }
        /// <summary>
        /// 菜单的形影工作类型
        /// 1、click：点击推事件
        /// 2、view：跳转URL
        /// 3、scancode_push：扫码推事件
        /// 4、scancode_waitmsg：扫码推事件且弹出“消息接收中”提示框
        /// 5、pic_sysphoto：弹出系统拍照发图
        /// 6、pic_photo_or_album：弹出拍照或者相册发图
        /// 7、pic_weixin：弹出微信相册发图器
        /// 8、location_select：弹出地理位置选择器
        /// 3-8  需要高版本 微信 5.4以上版本
        /// </summary>
        public string type { get; set; }
        /// <summary>
        /// 菜单key值，用于消息接口，不超过128字节
        /// </summary>
        public string key { get; set; }
        /// <summary>
        /// view类型必须，网页链接，用于点击菜单可打开链接，不超过256字节
        /// </summary>
        public string url { get; set; }
        /// <summary>
        /// 调用新增永久素材接口返回的合法media_id
        /// media_id类型和view_limited类型必须
        /// </summary>
        public string media_id { get; set; }
    }

}
